package com.github.byakkili.bim.protocol.protobuf.tcp;

import com.github.byakkili.bim.core.BimSession;
import com.github.byakkili.bim.core.handler.command.CommandFrame;
import com.github.byakkili.bim.core.support.util.BimSessionUtils;
import com.github.byakkili.bim.protocol.protobuf.BaseProtoBufCodec;
import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @author Guannian Li
 */
@Sharable
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TcpProtoBufCodec extends BaseProtoBufCodec<ByteBuf> {
    /**
     * 单例
     */
    public static final TcpProtoBufCodec INSTANCE = new TcpProtoBufCodec();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) {
        BimSession session = BimSessionUtils.get(ctx.channel());

        CommandFrame<Message> commandFrame = decodeToFrame(session, byteBuf);

        if (commandFrame != null) {
            out.add(commandFrame);
        }
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, CommandFrame<Message> frame, List<Object> out) {
        TcpProtoBufPacket packet = new TcpProtoBufPacket(frame);
        byte[] bytes = packet.toByteArray();

        out.add(Unpooled.wrappedBuffer(bytes));
    }
}
